<template>
  <div>
    <the-navigation>
      <template #header-controls>
        <div class="control-panel">
          <el-button type="success" class="control-btn success" @click="allowPlayback">
            <el-icon><video-play /></el-icon>
            <span>允许回放</span>
          </el-button>
          <el-button type="danger" class="control-btn danger" @click="forbidPlayback">
            <el-icon><video-pause /></el-icon>
            <span>禁止回放</span>
          </el-button>
        </div>
      </template>
    </the-navigation>
    
    <main class="main-content">
      <!-- 视频播放器区域 -->
      <section class="video-player-section">
        <div class="player-header">
          <div class="player-title">
            <el-icon><video-play /></el-icon>
            视频播放器
          </div>
          <div class="playback-controls">
            <span class="playback-label">播放速度:</span>
            <el-select v-model="playbackSpeed" class="player-input" @change="handlePlaybackRateChange">
              <el-option label="0.5x" :value="0.5" />
              <el-option label="0.75x" :value="0.75" />
              <el-option label="1.0x" :value="1.0" />
              <el-option label="1.25x" :value="1.25" />
              <el-option label="1.5x" :value="1.5" />
              <el-option label="2.0x" :value="2.0" />
            </el-select>
          </div>
        </div>
        
        <div class="player-wrapper">
          <video 
            ref="videoPlayer" 
            class="video-element" 
            controls 
            @loadeddata="onVideoLoad"
            @timeupdate="onTimeUpdate"
            @play="isPlaying = true"
            @pause="isPlaying = false"
            @ended="isPlaying = false"
            @error="handleVideoError"
          >
            <source :src="currentVideoSrc" type="video/mp4">
            您的浏览器不支持视频播放。
          </video>
          
          <!-- 加载中遮罩 -->
          <div class="loading-overlay" v-if="isLoading">
            <div class="loading-icon"></div>
            <span>视频加载中...</span>
          </div>
          
          <!-- 逐帧控制，与web端保持完全一致 -->
          <div class="frame-controls">
            <el-tooltip content="后退一帧 (←)" placement="top">
              <el-button type="primary" @click="prevFrame">
                <el-icon><arrow-left /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="前进一帧 (→)" placement="top">
              <el-button type="primary" @click="nextFrame">
                <el-icon><arrow-right /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
          
          
          <!-- 键盘快捷键提示 -->
          <div class="keyboard-shortcuts-info" v-if="!isLoading && currentVideoSrc">
            <div class="shortcut-item">
              <span class="key">←/→</span>
              <span class="action">帧控制</span>
            </div>
            <div class="shortcut-item">
              <span class="key">空格</span>
              <span class="action">播放/暂停</span>
            </div>
            <div class="shortcut-item">
              <span class="key">F</span>
              <span class="action">全屏</span>
            </div>
            <div class="shortcut-item">
              <span class="key">P</span>
              <span class="action">画中画</span>
            </div>
          </div>
        </div>
        
        <div class="video-info-panel">
          <div class="info-item">
            <span class="info-label">当前播放:</span>
            <span class="info-value">{{ currentVideo ? currentVideo.name : '未选择视频' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">文件大小:</span>
            <span class="info-value">{{ currentVideo ? currentVideo.size : '-' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">创建时间:</span>
            <span class="info-value">{{ currentVideo ? currentVideo.timestamp : '-' }}</span>
          </div>
        </div>
      </section>
      
      <!-- 视频列表区域 -->
      <section class="video-list-section">
        <div class="list-header">
          <div class="list-title">
            <el-icon><film /></el-icon>
            视频列表
          </div>
          <div class="list-actions">
            <el-button class="action-btn primary" @click="refreshList" :loading="isLoading">
              <el-icon><refresh /></el-icon>
              刷新列表
            </el-button>
            <el-button class="action-btn success" @click="handleUploadClick">
              <el-icon><upload /></el-icon>
              上传视频
            </el-button>
          </div>
        </div>
        
        <div class="record-controls">
          <el-input class="player-input" v-model="athleteId" placeholder="请输入选手编号" />
          <el-button class="record-btn" @click="startRecording" :disabled="isRecording || !mqttClient">
            <el-icon><video-camera /></el-icon>
            {{ isRecording ? '录制中...' : '开始记录' }}
          </el-button>
          <div class="record-tag" v-if="lastRecording">
            上次录制: {{ lastRecording }}
          </div>
        </div>
        
        <div class="video-list-wrapper">
          <el-table
            v-loading="isLoading"
            :data="paginatedVideos"
            style="width: 100%"
            :header-cell-style="{ background: '#f5f7fa' }"
            @row-click="handleVideoSelect"
            border
            stripe
            highlight-current-row
            row-class-name="video-row"
            v-if="videos.length > 0"
          >
            <el-table-column prop="name" label="视频名称" min-width="200">
              <template #default="scope">
                <div class="video-info" :class="{ 'current-playing': currentVideo && currentVideo.id === scope.row.id }">
                  <el-icon class="video-icon"><video-camera /></el-icon>
                  <el-tooltip :content="scope.row.name" placement="top">
                    <span class="video-name">{{ scope.row.name }}</span>
                  </el-tooltip>
                  <span class="playing-tag" v-if="currentVideo && currentVideo.id === scope.row.id">当前播放</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="duration" label="时长" width="80" align="center" />
            <el-table-column prop="size" label="大小" width="100" align="center" />
            <el-table-column prop="timestamp" label="创建时间" min-width="120" align="center" />
            <el-table-column label="操作" width="150" align="center" fixed="right">
              <template #default="scope">
                <div class="operation-cell">
                  <el-button
                    type="primary"
                    link
                    @click.stop="playVideo(scope.row)"
                  >
                    播放
                  </el-button>
                  <el-button
                    type="danger"
                    link
                    @click.stop="confirmDelete(scope.row)"
                  >
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 如果没有视频，显示空状态 -->
          <el-empty v-else description="暂无视频数据"></el-empty>
        </div>
        
        <div class="pagination-container" v-if="videos.length > pageSize">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="videos.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </section>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount, onActivated, onDeactivated } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import TheNavigation from '@/components/TheNavigation.vue'
import mqtt from 'mqtt'
import axios from 'axios'
import { VideoPlay, VideoPause, ArrowLeft, ArrowRight, Picture, FullScreen, Download, Refresh, VideoCamera, Film, Upload } from '@element-plus/icons-vue'

// MQTT连接相关
const mqttStatus = ref('disconnected')
const mqttClient = ref(null)

// 视频播放器状态
const videoPlayer = ref(null)
const isLoading = ref(false)
const isPlaying = ref(false)
const playbackSpeed = ref('1.0')
const currentVideo = ref(null)
const currentVideoSrc = ref('')
const videoProgress = ref(0)
const videoDuration = ref(0)
const hasShownLoadSuccess = ref(false)
const isPictureInPicture = ref(false)
const isFullscreen = ref(false)

// 视频录制状态
const isRecording = ref(false)
const athleteId = ref('')
const lastRecording = ref('')
const recordingStatus = ref('')

// 视频列表
const videos = ref([])

// 分页状态
const currentPage = ref(1)
const pageSize = ref(10)

// 分页后的视频列表
const paginatedVideos = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  return videos.value.slice(startIndex, startIndex + pageSize.value)
})

// 添加一个防缓存函数
const addCacheBuster = (url) => {
  if (!url) return '';
  // 检查URL是否已包含参数
  const hasParams = url.includes('?');
  // 添加时间戳参数，确保每次请求都是唯一的
  const timestamp = `_t=${new Date().getTime()}`;
  return url + (hasParams ? '&' : '?') + timestamp;
}

// 分页处理函数
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 连接MQTT服务器
function connectMqtt() {
  const options = {
    username: 'zxt',
    password: 'zyc123456',
    clean: true,
    connectTimeout: 4000,
    clientId: 'ipad_video_client_' + Math.random().toString(16).substring(2, 8)
  }

  console.log('🔄 正在连接MQTT服务器...')
  console.log(`连接信息: ws://192.168.31.245:8083/mqtt, 客户端ID: ${options.clientId}`)
  
  mqttClient.value = mqtt.connect('ws://192.168.31.245:8083/mqtt', options)

  // const options = {
  //   username: 'zxt',
  //   password: '554908',
  //   clean: true,
  //   connectTimeout: 4000,
  //   clientId: 'ipad_video_client_' + Math.random().toString(16).substring(2, 8)
  // }

  // console.log('🔄 正在连接MQTT服务器...')
  // console.log(`连接信息: ws://111.229.27.106:8083/mqtt, 客户端ID: ${options.clientId}`)
  
  // mqttClient.value = mqtt.connect('ws://111.229.27.106:8083/mqtt', options)

  mqttClient.value.on('connect', () => {
    console.log('🟢 MQTT服务器连接成功')
    mqttStatus.value = 'connected'
    
    // 订阅视频录制相关主题
    mqttClient.value.subscribe('roller/cam/MaixCAM/result', { qos: 1 }, (err) => {
      if (!err) {
        console.log('✅ 成功订阅录制结果主题')
      } else {
        console.error('❌ 订阅录制结果主题失败:', err)
      }
    })
  })

  mqttClient.value.on('message', (topic, message) => {
    try {
      console.log(`📩 收到MQTT消息: 主题=${topic}`)
      
      // 处理视频相关消息
      if (topic === 'roller/cam/MaixCAM/result') {
        handleMqttMessage(topic, message)
      }
    } catch (error) {
      console.error('❌ 处理MQTT消息出错:', error)
      ElMessage.error('数据格式错误')
    }
  })

  mqttClient.value.on('error', (err) => {
    console.error('❌ MQTT连接错误:', err)
    mqttStatus.value = 'disconnected'
    ElMessage.error('连接失败')
  })
  
  mqttClient.value.on('reconnect', () => {
    console.log('🔄 正在尝试重新连接MQTT服务器...')
  })
  
  mqttClient.value.on('close', () => {
    console.log('🔴 MQTT连接已关闭')
    mqttStatus.value = 'disconnected'
  })
}

// 处理MQTT消息
function handleMqttMessage(topic, payload) {
  console.log('收到MQTT消息:', topic, payload.toString())
  
  try {
    const message = JSON.parse(payload.toString())
    console.log('解析后的消息:', message)
    
    // 提取消息唯一标识
    const messageId = message.filename || message.player || JSON.stringify(message)
    // 使用普通变量而不是ref，避免响应式问题
    const lastProcessedMessageId = localStorage.getItem('lastProcessedMessageId') || ''
    
    console.log('消息ID:', messageId, '上次处理的消息ID:', lastProcessedMessageId)
    
    if (messageId === lastProcessedMessageId && message.status === 'uploaded') {
      console.log('该消息已处理过，跳过:', messageId)
      return
    }
    
    if (message.status === 'recording') {
      // 录制中
      recordingStatus.value = '录制中...'
      isRecording.value = true
    } else if (message.status === 'uploading') {
      // 上传中
      recordingStatus.value = '上传中...'
    } else if (message.status === 'uploaded') {
      // 上传完成
      recordingStatus.value = '完成'
      isRecording.value = false
      
      // 保存最后处理的消息ID
      localStorage.setItem('lastProcessedMessageId', messageId)
      
      // 更新录制信息
      lastRecording = `${message.filename} (选手${message.player})`
      
      // 显示成功消息
      ElMessage({
        type: 'success',
        message: `视频 ${message.filename} 录制完成`,
        duration: 5000,
        showClose: true
      })
      
      // 刷新视频列表
      refreshList()
    } else if (message.status === 'error') {
      // 错误
      recordingStatus.value = '错误'
      isRecording.value = false
      ElMessage.error(`录制失败: ${message.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('解析MQTT消息失败:', error)
  }
}

// 视频加载事件
function onVideoLoad() {
  console.log('视频加载完成');
  isLoading.value = false;
  if (videoPlayer.value) {
    // 设置播放速度
    videoPlayer.value.playbackRate = parseFloat(playbackSpeed.value);
    videoDuration.value = videoPlayer.value.duration;
    
    // 只显示一次加载成功消息
    if (!hasShownLoadSuccess.value) {
      ElMessage.success('视频加载成功');
      hasShownLoadSuccess.value = true;
    }
  }
}

// 视频错误处理
function handleVideoError(e) {
  console.error('视频加载错误:', e);
  isLoading.value = false;
  
  const videoElement = e.target;
  let errorMsg = '视频加载失败，请检查视频文件是否存在或网络连接是否正常。';
  if (videoElement.error) {
    switch (videoElement.error.code) {
      case videoElement.error.MEDIA_ERR_ABORTED:
        errorMsg = '视频播放被中止。';
        break;
      case videoElement.error.MEDIA_ERR_NETWORK:
        errorMsg = '网络错误导致视频下载失败。';
        break;
      case videoElement.error.MEDIA_ERR_DECODE:
        errorMsg = '视频解码失败，文件可能已损坏或格式不被支持。';
        break;
      case videoElement.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
        errorMsg = '视频资源格式不被支持。';
        break;
      default:
        errorMsg = '发生未知错误。';
        break;
    }
  }
  
  ElMessage.error(errorMsg);
  
  if (currentVideo.value) {
    console.log('当前视频加载失败:', currentVideo.value.name);
  }
}

// 视频播放进度更新事件
function onTimeUpdate() {
  if (videoPlayer.value) {
    videoProgress.value = videoPlayer.value.currentTime
  }
}

// 帧控制相关方法 - 与web端保持一致
const FRAME_STEP = 1/30 // 假设视频是30fps

// 跳转到上一帧
function prevFrame() {
  if (videoPlayer.value) {
    videoPlayer.value.pause();
    videoPlayer.value.currentTime = Math.max(0, videoPlayer.value.currentTime - FRAME_STEP);
  }
}

// 跳转到下一帧
function nextFrame() {
  if (videoPlayer.value) {
    videoPlayer.value.pause();
    videoPlayer.value.currentTime = Math.min(
      videoPlayer.value.duration || 0,
      videoPlayer.value.currentTime + FRAME_STEP
    );
  }
}

// 播放/暂停切换
function togglePlay() {
  if (!videoPlayer.value) return;
  
  if (videoPlayer.value.paused) {
    videoPlayer.value.play();
    isPlaying.value = true;
  } else {
    videoPlayer.value.pause();
    isPlaying.value = false;
  }
}

// 播放视频
function playVideo(video) {
  if (!video || !video.url) {
    ElMessage.warning('视频链接无效');
    return;
  }
  
  currentVideo.value = video;
  
  // 添加防缓存参数到URL - 这是web端正确的方式
  const noCacheUrl = addCacheBuster(video.url);
  console.log('播放视频URL:', noCacheUrl);
  
  // 开始加载
  isLoading.value = true;
  hasShownLoadSuccess.value = false;
  
  // 设置视频源
  if (videoPlayer.value) {
    videoPlayer.value.src = noCacheUrl;
    videoPlayer.value.load();
    videoPlayer.value.playbackRate = parseFloat(playbackSpeed.value);
  } else {
    // 如果视频元素还没准备好，先设置URL
    currentVideoSrc.value = noCacheUrl;
  }
  
  // 通知用户
  ElMessage.success(`正在播放: ${video.name}`);
}

// 视频选择处理
function handleVideoSelect(row) {
  playVideo(row);
}

// 确认删除视频
function confirmDelete(video) {
  ElMessageBox.confirm(`确定要删除视频 "${video.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 显示加载状态
      const loadingInstance = ElLoading.service({
        text: '正在删除视频...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      
      // 使用新的删除API
      const response = await axios.delete(`http://111.229.27.106:3000/api/videos/${encodeURIComponent(video.name)}`);
      
      loadingInstance.close();
      
      if (response.data && response.data.code === 200) {
        // 从列表中移除已删除的视频
        videos.value = videos.value.filter(item => item.id !== video.id);
        ElMessage.success(`视频 "${video.name}" 删除成功`);
        
        // 如果删除的是当前播放的视频，则清空当前视频
        if (currentVideo.value && currentVideo.value.id === video.id) {
          currentVideo.value = null;
          currentVideoSrc.value = '';
        }
      } else {
        const errorMsg = response.data ? (response.data.message || '未知错误') : '未知错误';
        ElMessage.error(`删除失败: ${errorMsg}`);
      }
    } catch (error) {
      loadingInstance.close();
      console.error('删除视频出错:', error);
      ElMessage.error(`删除出错: ${error.message || '网络错误，请稍后重试'}`);
    }
  }).catch(() => {
    // 取消操作
    ElMessage.info('已取消删除');
  })
}

// 刷新视频列表
async function refreshList() {
  isLoading.value = true;
  try {
    // 使用新的服务器地址和API路径
    const response = await axios.get('http://111.229.27.106:3000/api/videos');
    console.log('视频列表接口返回数据:', response.data);
    
    if (!response.data || response.data.length === 0) {
      console.log('API返回空数据');
      videos.value = [];
      return;
    }
    
    // 格式化视频列表数据
    videos.value = response.data.map(item => {
      return {
        id: item.id,
        name: item.video_name,
        duration: '--',
        size: item.size,
        timestamp: item.createTime,
        url: `http://111.229.27.106:3000${item.video_address}`
      };
    });
    
    ElMessage.success('视频列表已刷新');
  } catch (error) {
    console.error('获取视频列表失败:', error);
    ElMessage.error('获取视频列表失败');
  } finally {
    isLoading.value = false;
  }
}

// 加载示例视频
function loadSampleVideos() {
  console.log('加载示例视频');
  
  // 使用web端相同的测试数据格式
  videos.value = [
    {
      id: 1,
      name: 'sample1.mp4',
      duration: '1:30',
      size: '10.5 MB',
      timestamp: new Date().toLocaleString(),
      url: 'http://localhost:3000/videos/sample1.mp4'
    },
    {
      id: 2,
      name: 'sample2.mp4',
      duration: '2:45',
      size: '15.2 MB',
      timestamp: new Date().toLocaleString(),
      url: 'http://localhost:3000/videos/sample2.mp4'
    }
  ];
  
  ElMessage.warning('无法连接到视频服务器，已加载示例视频');
}

// 开始录制
function startRecording() {
  if (!athleteId.value) {
    ElMessage.warning('请先输入选手编号')
    return
  }
  
  if (mqttClient.value && mqttStatus.value === 'connected') {
    // 发送录制命令
    const publishTopic = 'roller/cam/MaixCAM/pub/'
    const publishData = { 
      connect: 'user1',
      race: 'on',
      player: athleteId.value
    }
    
    console.log(`📤 发送开始录制指令: 主题=${publishTopic}, 数据=`, publishData)
    
    mqttClient.value.publish(publishTopic, JSON.stringify(publishData), { qos: 1 }, (error) => {
      if (error) {
        console.error('MQTT消息发送失败:', error)
        ElMessage.error(`发送失败: ${error.message}`)
        return
      }
      
      isRecording.value = true
      recordingStatus.value = '等待摄像头响应...'
      ElMessage.success(`已向摄像机发送选手 ${athleteId.value} 录制指令`)
    })
  } else {
    ElMessage.warning('MQTT未连接，无法发送录制指令')
  }
}

// 上传相关
const uploadRef = ref(null)
const uploadProgress = ref(0)
const isUploading = ref(false)

// 处理上传按钮点击
function handleUploadClick() {
  // 创建一个隐藏的文件输入框
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.mp4,.webm,.ogg,.mov,.avi,.wmv,.mkv'
  input.multiple = false
  input.style.display = 'none'
  
  // 监听文件选择
  input.onchange = (e) => {
    const file = e.target.files[0]
    if (file) {
      uploadVideo(file)
    }
  }
  
  // 触发文件选择
  input.click()
}

// 上传视频
async function uploadVideo(file) {
  // 检查文件大小（500MB限制）
  const maxSize = 500 * 1024 * 1024 // 500MB
  if (file.size > maxSize) {
    ElMessage.error('文件大小不能超过500MB')
    return
  }
  
  // 检查文件类型
  const allowedTypes = ['video/mp4', 'video/webm', 'video/ogg', 'video/quicktime', 'video/x-msvideo', 'video/x-ms-wmv', 'video/x-matroska']
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error('不支持的视频格式')
    return
  }
  
  // 创建FormData
  const formData = new FormData()
  formData.append('video', file)
  
  try {
    isUploading.value = true
    uploadProgress.value = 0
    
    // 显示上传进度
    const loadingInstance = ElLoading.service({
      text: '正在上传视频...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    // 发送上传请求
    const response = await axios.post('http://111.229.27.106:3000/api/videos/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        const progress = (progressEvent.loaded / progressEvent.total) * 100
        uploadProgress.value = Math.round(progress)
        loadingInstance.setText(`正在上传视频... ${uploadProgress.value}%`)
      }
    })
    
    loadingInstance.close()
    
    if (response.data && response.data.code === 200) {
      ElMessage.success('视频上传成功')
      // 刷新视频列表
      refreshList()
    } else {
      const errorMsg = response.data ? (response.data.message || '未知错误') : '未知错误'
      ElMessage.error(`上传失败: ${errorMsg}`)
    }
  } catch (error) {
    console.error('上传视频出错:', error)
    ElMessage.error(`上传出错: ${error.message || '网络错误，请稍后重试'}`)
  } finally {
    isUploading.value = false
    uploadProgress.value = 0
  }
}

// 监听播放速度变化
watch(playbackSpeed, (newSpeed) => {
  if (videoPlayer.value) {
    videoPlayer.value.playbackRate = parseFloat(newSpeed)
  }
})

// 添加键盘事件处理
function handleKeydown(e) {
  if (document.activeElement.tagName === 'INPUT') return
  
  switch (e.key) {
    case 'ArrowLeft':
      e.preventDefault()
      prevFrame()
      break
    case 'ArrowRight':
      e.preventDefault()
      nextFrame()
      break
    case ' ': // 空格键
      e.preventDefault()
      togglePlay()
      break
    case 'f': // f键全屏
    case 'F':
      e.preventDefault()
      toggleFullscreen()
      break
    case 'p': // p键画中画
    case 'P':
      e.preventDefault()
      togglePictureInPicture()
      break
  }
}

// 组件挂载时连接MQTT和初始化
onMounted(() => {
  connectMqtt();
  refreshList();
  
  // 添加键盘事件监听
  window.addEventListener('keydown', handleKeydown);
  
  // 监听全屏变化事件
  document.addEventListener('fullscreenchange', handleFullscreenChange);
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
  document.addEventListener('mozfullscreenchange', handleFullscreenChange);
  document.addEventListener('MSFullscreenChange', handleFullscreenChange);
  
  // 监听画中画变化事件
  videoPlayer.value?.addEventListener('enterpictureinpicture', () => {
    isPictureInPicture.value = true;
  });
  
  videoPlayer.value?.addEventListener('leavepictureinpicture', () => {
    isPictureInPicture.value = false;
  });
});

// 组件激活时执行（从其他页面返回时）
onActivated(() => {
  console.log('视频回放页面被激活')
  
  // 恢复MQTT连接
  if (!mqttClient.value || !mqttClient.value.connected) {
    console.log('恢复MQTT连接')
    connectMqtt()
  }
  
  // 如果之前有播放的视频，尝试恢复播放状态
  if (currentVideo.value && videoPlayer.value) {
    console.log('恢复视频播放状态')
    
    // 如果之前是播放状态，则继续播放
    if (isPlaying.value) {
      videoPlayer.value.play().catch(error => {
        console.error('恢复视频播放失败:', error)
        isPlaying.value = false
      })
    }
    
    // 恢复播放速度
    videoPlayer.value.playbackRate = parseFloat(playbackSpeed.value)
  }
})

// 组件停用时执行（切换到其他页面时）
onDeactivated(() => {
  console.log('视频回放页面被停用')
  
  // 如果有视频在播放，记住状态但暂停播放以节省资源
  if (videoPlayer.value && !videoPlayer.value.paused) {
    console.log('暂停视频播放')
    videoPlayer.value.pause()
    // 保持isPlaying状态，以便返回时可以恢复
  }
  
  // 不断开MQTT连接，只在组件销毁时断开
  console.log('保持MQTT连接')
})

// 组件销毁前清除监听器
onBeforeUnmount(() => {
  // 移除键盘事件监听
  window.removeEventListener('keydown', handleKeydown);
  
  // 移除全屏变化事件监听
  document.removeEventListener('fullscreenchange', handleFullscreenChange);
  document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
  document.removeEventListener('mozfullscreenchange', handleFullscreenChange);
  document.removeEventListener('MSFullscreenChange', handleFullscreenChange);
  
  // 移除画中画事件监听
  videoPlayer.value?.removeEventListener('enterpictureinpicture', () => {});
  videoPlayer.value?.removeEventListener('leavepictureinpicture', () => {});
  
  if (mqttClient.value) {
    mqttClient.value.end();
  }
});

// 切换全屏
function toggleFullscreen() {
  if (!videoPlayer.value) return
  
  try {
    if (!document.fullscreenElement) {
      // 进入全屏
      if (videoPlayer.value.requestFullscreen) {
        videoPlayer.value.requestFullscreen()
      } else if (videoPlayer.value.webkitRequestFullscreen) { /* Safari */
        videoPlayer.value.webkitRequestFullscreen()
      } else if (videoPlayer.value.msRequestFullscreen) { /* IE11 */
        videoPlayer.value.msRequestFullscreen()
      }
      isFullscreen.value = true
      ElMessage.success('已进入全屏模式')
    } else {
      // 退出全屏
      if (document.exitFullscreen) {
        document.exitFullscreen()
      } else if (document.webkitExitFullscreen) { /* Safari */
        document.webkitExitFullscreen()
      } else if (document.msExitFullscreen) { /* IE11 */
        document.msExitFullscreen()
      }
      isFullscreen.value = false
      ElMessage.success('已退出全屏模式')
    }
  } catch (error) {
    console.error('全屏操作失败:', error)
    ElMessage.error('全屏操作失败，请手动使用视频控制栏的全屏按钮')
  }
}

// 切换画中画模式
async function togglePictureInPicture() {
  if (!videoPlayer.value) return
  
  try {
    if (document.pictureInPictureElement) {
      // 退出画中画
      await document.exitPictureInPicture()
      isPictureInPicture.value = false
      ElMessage.success('已退出画中画模式')
    } else if (document.pictureInPictureEnabled) {
      // 进入画中画
      await videoPlayer.value.requestPictureInPicture()
      isPictureInPicture.value = true
      ElMessage.success('已进入画中画模式')
    } else {
      ElMessage.warning('您的浏览器不支持画中画功能')
    }
  } catch (error) {
    console.error('画中画操作失败:', error)
    ElMessage.error('画中画操作失败')
  }
}

// 处理全屏状态变化
function handleFullscreenChange() {
  isFullscreen.value = !!document.fullscreenElement;
}

// 处理播放速度变化
function handlePlaybackRateChange(rate) {
  console.log('播放速度变更为:', rate);
  if (videoPlayer.value) {
    videoPlayer.value.playbackRate = rate;
    ElMessage.success(`播放速度已调整为 ${rate}x`);
  }
}

// 允许回放
function allowPlayback() {
  if (mqttClient.value && mqttStatus.value === 'connected') {
    const publishTopic = 'roller/pile/pub/a'
    const publishData = { video: 'on' }
    console.log(`📤 发送允许回放指令: 主题=${publishTopic}, 数据=`, publishData)
    
    mqttClient.value.publish(publishTopic, JSON.stringify(publishData))
    ElMessage.success('已允许视频回放')
  } else {
    ElMessage.warning('MQTT未连接，无法发送指令')
  }
}

// 禁止回放
function forbidPlayback() {
  if (mqttClient.value && mqttStatus.value === 'connected') {
    const publishTopic = 'roller/pile/pub/a'
    const publishData = { video: 'off' }
    console.log(`📤 发送禁止回放指令: 主题=${publishTopic}, 数据=`, publishData)
    
    mqttClient.value.publish(publishTopic, JSON.stringify(publishData))
    ElMessage.success('已禁止视频回放')
  } else {
    ElMessage.warning('MQTT未连接，无法发送指令')
  }
}
</script>

<style scoped>
/* 视频播放器样式 */
.video-player-section {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  border-left: 4px solid #409EFF;
  margin-bottom: 20px;
}

.player-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid rgba(228, 232, 236, 0.8);
  background: rgba(255, 255, 255, 0.8);
}

.player-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 10px;
  position: relative;
  padding-left: 15px;
}

.player-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 5px;
  height: 18px;
  background: linear-gradient(135deg, #409EFF 0%, #36acfe 100%);
  border-radius: 3px;
}

.player-title :deep(i) {
  color: #409EFF;
  font-size: 20px;
}

.player-wrapper {
  position: relative;
  min-height: 400px;
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.video-element {
  width: 100%;
  height: 100%;
  object-fit: contain;
  z-index: 1;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
  gap: 12px;
  z-index: 10;
}

.loading-icon {
  width: 32px;
  height: 32px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top: 3px solid #fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 视频控制面板 */
.video-controls {
  display: none; /* 不再使用这个类 */
}

.video-info-panel {
  background: #f5f7fa;
  padding: 16px 20px;
  border-top: 1px solid rgba(228, 232, 236, 0.8);
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.info-label {
  font-size: 13px;
  color: #909399;
}

.info-value {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  word-break: break-all;
}

/* 视频列表样式 */
.video-list-section {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  border-left: 4px solid #67c23a;
  flex: 1;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid rgba(228, 232, 236, 0.8);
  background: rgba(255, 255, 255, 0.8);
}

.list-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 10px;
  position: relative;
  padding-left: 15px;
}

.list-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 5px;
  height: 18px;
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  border-radius: 3px;
}

.list-title :deep(i) {
  color: #67c23a;
  font-size: 20px;
}

.list-actions {
  display: flex;
  gap: 10px;
}

.action-btn {
  padding: 8px 16px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  border: none !important;
  transition: all 0.3s;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
}

.action-btn.primary {
  background: linear-gradient(135deg, #409EFF 0%, #36acfe 100%) !important;
  color: white !important;
}

.action-btn.primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(64, 158, 255, 0.3);
}

.action-btn.info {
  background: linear-gradient(135deg, #909399 0%, #a6a9ad 100%) !important;
  color: white !important;
}

.action-btn.info:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(144, 147, 153, 0.3);
}

.action-btn.success {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%) !important;
  color: white !important;
}

.action-btn.success:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(103, 194, 58, 0.3);
}

.record-controls {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 16px 20px;
  background: #f5f7fa;
  border-bottom: 1px solid rgba(228, 232, 236, 0.8);
  flex-wrap: wrap;
}

.player-input {
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  width: 180px;
  transition: all 0.3s;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.record-btn {
  padding: 8px 16px;
  border-radius: 6px;
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%) !important;
  color: white !important;
  border: none !important;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 4px 8px rgba(103, 194, 58, 0.2);
}

.record-btn:hover:not([disabled]) {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(103, 194, 58, 0.3);
}

.record-tag {
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 13px;
  background: rgba(103, 194, 58, 0.1);
  color: #67c23a;
  border: 1px solid rgba(103, 194, 58, 0.2);
  display: inline-block;
  flex: 1;
  white-space: normal;
  line-height: 1.4;
}

.video-list-wrapper {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  max-height: 400px;
}

.video-info {
  display: flex;
  align-items: center;
  gap: 8px;
  position: relative;
  padding: 8px 0;
}

.video-icon {
  color: #409EFF;
  font-size: 16px;
  flex-shrink: 0;
}

.video-name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 160px;
  display: inline-block;
  line-height: 1.4;
  flex: 1;
}

.playing-tag {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  background: #67c23a;
  color: white;
}

.video-row:hover {
  background-color: #f0f9ff !important;
  cursor: pointer;
}

.current-playing {
  color: #409EFF;
  font-weight: bold;
}

.current-playing .video-icon {
  color: #409EFF;
  animation: pulse 1.5s ease infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.6; }
  100% { opacity: 1; }
}

.operation-cell {
  display: flex;
  justify-content: center;
  flex-wrap: nowrap;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 16px 20px;
  border-top: 1px solid rgba(228, 232, 236, 0.8);
  background: white;
}

/* 响应式设计 */
@media (max-width: 1180px) {
  .video-info-panel {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .player-wrapper {
    min-height: 350px;
  }
}

@media (max-width: 960px) {
  .player-wrapper {
    min-height: 300px;
  }
  
  .video-info-panel {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .list-header, .record-controls {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .list-actions, .record-controls {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .video-info-panel {
    grid-template-columns: 1fr;
  }
  
  .player-wrapper {
    min-height: 250px;
  }
  
  .video-list-wrapper {
    max-height: 300px;
  }
}

/* 键盘快捷键提示 */
.keyboard-shortcuts-info {
  position: absolute;
  top: 20px;
  right: 20px;
  background: rgba(0, 0, 0, 0.6);
  padding: 10px 15px;
  border-radius: 8px;
  color: white;
  font-size: 12px;
  z-index: 10;
  display: flex;
  flex-direction: column;
  gap: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
}

.shortcut-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.key {
  background: #409EFF;
  padding: 2px 6px;
  border-radius: 4px;
  font-weight: bold;
  min-width: 24px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.action {
  opacity: 0.9;
}

/* 帧控制样式 - 与web端保持一致 */
.frame-controls {
  position: absolute;
  bottom: 70px;
  left: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(0, 0, 0, 0.6);
  padding: 8px;
  border-radius: 8px;
  z-index: 5;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
}

.frame-controls .el-button {
  background: #409EFF;
  border: none;
  padding: 8px;
  height: 32px;
  width: 32px;
  transition: all 0.3s;
}

.frame-controls .el-button:hover {
  background: #66b1ff;
  transform: translateY(-2px);
}

.frame-controls .el-icon {
  color: #fff;
  font-size: 16px;
}

/* 高级控制 */
.advanced-controls {
  position: absolute;
  bottom: 70px;
  right: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(0, 0, 0, 0.6);
  padding: 8px;
  border-radius: 8px;
  z-index: 5;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
}

.advanced-controls .el-button {
  background: #409EFF;
  border: none;
  padding: 8px;
  height: 32px;
  width: 32px;
  transition: all 0.3s;
}

.advanced-controls .el-button:hover {
  background: #66b1ff;
  transform: translateY(-2px);
}

.advanced-controls .el-icon {
  color: #fff;
  font-size: 16px;
}

/* 控制按钮组 */
.control-panel {
  position: relative;
  right: 130px;
  display: flex;
  gap: 15px;
  z-index: 5;
}

.control-btn {
  border: none !important;
  position: relative;
  overflow: hidden;
  border-radius: 12px !important;
  font-weight: 600 !important;
  min-width: 120px !important;  /* 从70px改为120px */
  padding: 10px 20px !important;  /* 从16px改为20px，增加内边距 */
}

.control-btn.success {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%) !important;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

.control-btn.success:hover {
  box-shadow: 0 6px 16px rgba(103, 194, 58, 0.4);
  transform: translateY(-2px);
}

.control-btn.danger {
  background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%) !important;
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
}

.control-btn.danger:hover {
  box-shadow: 0 6px 16px rgba(245, 108, 108, 0.4);
  transform: translateY(-2px);
}

.control-btn::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0));
  z-index: 0;
}

.control-btn :deep(i),
.control-btn :deep(span) {
  position: relative;
  z-index: 1;
}
</style> 